package com.yuju.persist.util;


import java.net.URL;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;

import com.alibaba.fastjson.JSON;

/**
 * Ehcache操作类
 * 数据统一用字符串存储
 * 
 * @author rising.xin
 *
 */
public class EhcacheUtil {

	private static final String path = "/ehcache_custom.xml";  
	  
    private CacheManager manager;  
  
    private static EhcacheUtil ehCache;
    
    public static final String CACHE_NAME_DATABOOK = "databook";
    
    private EhcacheUtil(String path) {  
        final URL myUrl = this.getClass().getResource(path); 
        Configuration xmlConfig = new XmlConfiguration(myUrl); 
        manager = CacheManagerBuilder.newCacheManager(xmlConfig); 
        manager.init();
    }  
  
	public static EhcacheUtil getInstance() {  
        if (ehCache== null) {  
            ehCache= new EhcacheUtil(path);  
        }  
        return ehCache;  
    }
    
	/**
	 * 往缓存里添加元素
	 * 
	 * @param cacheName 缓存块名称
	 * 
	 * @param key 缓存元素key
	 * 
	 * @param value 缓存元素内容
	 */
	public void put(String cacheName,String key, Object value){
		String valueJson = JSON.toJSONString(value);
    	Cache<String, String> cache = manager.getCache(cacheName, String.class, String.class);
    	if(null != cache){
    		if(cache.containsKey(key)){
				//key已存在
    			cache.remove(key);
			}
			cache.put(key, valueJson);
    	}
    	
    } 
	
	/**
	 * 根据数据类型获取缓存内容
	 * 
	 * @param cacheName 缓存块名称
	 * 
	 * @param key 缓存元素key
	 * 
	 * @param t 缓存内容类型
	 * @return
	 */
	public <T> T get(String cacheName,String key,Class<T> t){
		Cache<String, String> cache = manager.getCache(cacheName, String.class, String.class);
		if(null != cache){
			String value = cache.get(key);
			if(null != value && value.trim().length() > 0){
				return JSON.parseObject(value, t);
			}
		}
		return null;
	}
	
	/**
	 * 根据缓存块名称清空缓存
	 * 
	 * @param cacheName 缓存块名称
	 */
	public void clear(String cacheName){
		Cache<String, String> cache = manager.getCache(cacheName, String.class, String.class);
		if(null != cache){
			cache.clear();
		}
	}
	
	/**
	 * 根据缓存块名称和元素key删除元素
	 * 
	 * @param cacheName 缓存块名称
	 * 
	 * @param key 缓存元素key
	 */
	public void del(String cacheName,String key){
		Cache<String, String> cache = manager.getCache(cacheName, String.class, String.class);
		if(null != cache){
			if(cache.containsKey(key)){
				cache.remove(key);
			}
		}
	}
	
}
